package com.easy.carl.algorithm.String;

/**
 * 541. 反转字符串 II
 */
public class ReverseStr541 {

    public String reverseStr(String s, int k) {
        char[] chars = s.toCharArray();
        int len = chars.length;
        int end = len - 1;
        int start = 0;
        while (start < chars.length) {
            //start到end之间长度大于2k
            if (start + 2 * k - 1 <= end) {
                reverseStr(chars, start, start + k - 1);
            } else if (start + k - 1 <= end) {//k
                reverseStr(chars, start, start + k - 1);
            } else {
                reverseStr(chars, start, end);
            }
            start = start + 2 * k;
        }
        return String.valueOf(chars);
    }

    public void reverseStr(char[] chars, int start, int end) {
        while (start < end) {
            char c = chars[start];
            chars[start] = chars[end];
            chars[end] = c;
            start++;
            end--;
        }
    }

    public static void main(String[] args) {
        String s = "abcd";
        ReverseStr541 reverseStr541 = new ReverseStr541();
        System.out.println(reverseStr541.reverseStr(s, 2));
    }
}
